package website.haicheng.core.util;

import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 582895699@qq.com
 * @time: 2021/2/9 下午 09:37
 */
public class JWTUtil {
    /**
     * 密钥加盐
     */
    private static final String KEY = "6784f93a-8e49-4308-a673-eedb46be6f5d";

    /**
     * 过期时间  1小时
     */
    private static final long TTL = TimeUnit.HOURS.toMillis(10L);

    /**
     * 生成JWT
     */
    public static String createToken(String subject, Long userId) {

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(IdWorker.get32UUID())
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, KEY)
                .claim("userInfo", userId);
        builder.setExpiration(new Date(nowMillis + TTL));
        return builder.compact();

    }

    /**
     * 解析JWT
     */
    public static Claims parseToken(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    /**
     * 从token中获取获取账号
     *
     * @param request
     * @return
     */
    public static String getAccountFromToken(HttpServletRequest request) {
        String token = getTokenFromHeader(request);
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 从token中获取获取用户 id
     *
     * @param request
     * @return
     */
    public static int getUserIdFromToken(HttpServletRequest request) {
        String token = getTokenFromHeader(request);
        Claims claims = parseToken(token);
        return (int) claims.get("userInfo");
    }

    /**
     * 从header中获取token
     *
     * @param request
     * @return
     */
    public static String getTokenFromHeader(HttpServletRequest request) {
        String authHeader = ServletUtil.getHeader(request, "Authorization", StandardCharsets.UTF_8);
        return authHeader.replace("Bearer ", "");
    }
}
